package com.weixin.common.security.aspect;

import com.weixin.common.core.constant.SecurityConstants;
import com.weixin.common.core.exception.BaseException;
import com.weixin.common.core.utils.ServletUtil;
import com.weixin.common.security.annotations.Inner;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

/**
 * @version 1.0.0
 * @className: InnerAuthAspect
 * @description: 内部注解AOP拦截
 * @author: zhangjunfa
 * @date: 2023/6/15 15:46
 */
@Aspect
@Component
public class InnerAuthAspect implements Ordered {

    @Around("@annotation(innerAuth)")
    public Object innerAround(ProceedingJoinPoint joinPoint, Inner innerAuth) throws Throwable {
        String source = ServletUtil.getRequest().getHeader(SecurityConstants.FROM_SOURCE);
        // 内部请求验证
        if (!StringUtils.equals(SecurityConstants.INNER, source))
        {
            throw new BaseException("没有内部访问权限，不允许访问");
        }

        String userId = ServletUtil.getRequest().getHeader(SecurityConstants.DETAILS_USER_ID);
        String username = ServletUtil.getRequest().getHeader(SecurityConstants.DETAILS_USERNAME);
        // 用户信息验证
        if (innerAuth.isUser() && (StringUtils.isEmpty(userId) || StringUtils.isEmpty(username)))
        {
            throw new BaseException("没有设置用户信息，不允许访问 ");
        }

        return joinPoint.proceed();
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 1;
    }
}
